import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import merge from 'lodash/merge'
import {clearLoginInfo} from '@/utils'

const http = axios.create({
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  config.headers['token'] = Vue.cookie.get('token') // 请求头带上token
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (response.data && response.data.code === 401) { // 401, token失效
    clearLoginInfo()
    router.push({name: 'login'})
  }
  return response
}, error => {
  return Promise.reject(error)
})

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefaultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefaultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefaultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefaultData 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefaultData = true, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefaultData ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export function fileDownload(url) {
  let header = {
    'token': Vue.cookie.get('token')
  }
  return new Promise((resolve, reject) => {
    http.post(url, {}, {
      headers: header,
      params: {},
      responseType: 'blob'
    }).then(res => {
      if (res.data.type === 'text/xml') {
        const content = res.data;
        const blob = new Blob([content]); //构造一个blob对象来处理数据
        const fileName = new Date().getTime() + '.xlsx';
        if ('download' in document.createElement('a')) {
          const link = document.createElement('a');
          link.download = fileName;
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        } else {
          navigator.msSaveBlob(blob, fileName);
        }
        resolve(res)
      } else if (res.data.type === 'application/json') {
        let reader = new FileReader();
        reader.readAsText(res.data, 'utf-8');
        reader.onload = function () {
          let data = JSON.parse(reader.result);
          reject(data.msg);
        }
      } else {
        reject('不支持的下载文件类型');
      }
    }).catch(error => {
      reject(error);
    })
  });
}

export function importExcel(url, formData) {
  let header = {
    'token': Vue.cookie.get('token'),
    'Content-type': 'multipart/form-data',
  }
  return new Promise((resolve, reject) => {
    http.post(url, formData, {
      headers: header
    })
      .then(response => {
        resolve(response);
      })
      .catch(error => {
        reject(error);
      });
  });
}

export function pendFormData(formdata, key, value){
  if (value == null || value == undefined){
    return null;
  }
  return formdata.append(key, value)
}

export default http
